home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 6234 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.2 KB  |  44 lines

  1. Newsgroups: comp.lang.c++
  2. Path: hearst.acc.Virginia.EDU!maxwell!gcl8a
  3. From: gcl8a@Virginia.EDU (Gregory Carl Lewin)
  4. Subject: type-casting in multi-inheritance
  5. Message-ID: <DMn7Ix.G9@Virginia.EDU>
  6. Organization: University of Virginia
  7. Date: Mon, 12 Feb 1996 03:11:20 GMT
  8.  
  9. I am a bit fuzzy about casting from pointers to derived objects
  10. to base classes when you are using multiple inheritance.
  11. Perhaps someone could explain the following to me.  Consider
  12. the arrangement:
  13.  
  14. class Base1 {};
  15. class Base2 {};
  16. class Derived12 : public Base1, Base2 {};
  17.  
  18. Base1 b1;
  19. Base2 b2;
  20. Derived12 d12;
  21.  
  22. void foo(void) {
  23. Base1* pb1;
  24. pb1=&b1;
  25. pb1=&d12;
  26.  
  27. Base2* pb2;
  28. pb2=&b2;
  29. pb2=&d12; //ERROR: Cannot convert pointer
  30. pb2=(Base2*) &d12;  //OK: But is it ALWAYS safe?
  31.  
  32. }
  33.  
  34. Because Derived 12 is publicly derived from Base1 and Base2, I
  35. would have expected the conversion of &d12 to a Base2* to be
  36. automatic; however, the comiler balks.  The subsequent explicit
  37. conversion works, and the program seems to act appropriately,
  38. but using the explicit type-cast scares me.  Can someone
  39. explain why this is and if this is the "correct" way around the
  40. problem (alternatives being virtual inheritance with class Base
  41. being a base for Base1 and Base2, and ???).
  42.  
  43. Greg Lewin
  44.